<template>
  <div>
    <div>
      <FormPanel
        ref="formPanel"
        :list="formList"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />

      <el-form :model="ruleForm" ref="addRuleForm" label-width="110px" :rules="rules" class="font">
        <el-form-item label="跟进结果" prop="actionStatus" v-if="clueStatus !==70001011?true:false">
          <el-input v-model="ruleForm.actionStatus" style="display:none;"></el-input>
          <!-- 无效:15171009 待定:15171007 战败:15171005 继续:15171004 预约:15171008 -->
          <el-button :class="isBlue2" @click="selectBtn(15171005)" v-show="isShowDefeat">战败</el-button>
          <el-button :class="isBlue3" @click="selectBtn(15171004)">继续</el-button>
          <el-button :class="isBlue4" @click="selectBtn(15171008)">预约</el-button>
        </el-form-item>
        <el-form-item label="跟进结果" prop="actionStatus" v-else-if="clueStatus ==70001011?true:false">
          <el-input v-model="ruleForm.actionStatus" style="display:none;"></el-input>
          <el-button :class="isBlue" @click="selectBtn(15171009)">无效</el-button>
          <el-button :class="isBlue1" @click="selectBtn(15171007)">待定</el-button>
          <!-- <el-button :class="isBlue2" @click="selectBtn(15171005)">战败</el-button> -->
          <el-button :class="isBlue3" @click="selectBtn(15171004)">继续</el-button>
          <el-button :class="isBlue4" @click="selectBtn(15171008)">预约</el-button>
        </el-form-item>
      </el-form>
      <FormPanel
        ref="formPanel2"
        :list="formList2"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />

      <el-form :model="ruleForm" ref="addRuleForm" label-width="110px" :rules="rules" class="font">
        <el-form-item
          v-if="this.selectBtnNum == 15171009?true:false"
          label="无效原因"
          prop="invalidReason"
        >
          <el-select v-model="ruleForm.invalidReason" clearable placeholder="请选择">
            <el-option
              v-for="item in invalidReasonList"
              :key="item.basedataId"
              :label="item.basedataName"
              :value="item.basedataId"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 待定 -->
        <template v-else-if="this.selectBtnNum == 15171007?true:false">
          <el-form-item label="下次跟进时间" prop="nextActionedDateB">
            <el-date-picker
              v-model="ruleForm.nextActionedDateB"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="下次跟进备注">
            <el-input type="textarea" v-model="ruleForm.taskName"></el-input>
          </el-form-item>
        </template>
        <!-- 继续 -->
        <template v-else-if="this.selectBtnNum == 15171004?true:false">
          <el-form-item label="下次跟进时间" prop="nextActionedDate">
            <el-date-picker
              v-model="ruleForm.nextActionedDate"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
              :picker-options=" pickerOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="下次跟进备注">
            <el-input type="textarea" v-model="ruleForm.taskName"></el-input>
          </el-form-item>
        </template>

        <template v-else-if="this.selectBtnNum == 15171005?true:false">
          <el-form-item label="战败原因" prop="resultReason">
            <el-select
              v-model="ruleForm.resultReason"
              clearable
              placeholder="请选择"
              @change="currentSel"
            >
              <el-option
                v-for="item in defeatReasonList"
                :key="item.defeatReasonId"
                :label="item.drDesc"
                :value="item.defeatReasonId"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 战败经销商 -->
          <el-form-item
            v-if="accordingObj && according2ReasonObj[ruleForm.resultReason].paramName === 'defeatReasonsIdThree'"
            :label="according2ReasonObj[ruleForm.resultReason].label"
            prop="defeatReasonsIdDealer"
          >
            <el-select v-model="ruleForm.defeatReasonsIdDealer" clearable placeholder="请选择">
              <el-option
                v-for="item in according2ReasonObj[ruleForm.resultReason].list"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 战败车型 -->
          <el-form-item
            v-else-if="accordingObj && according2ReasonObj[ruleForm.resultReason].paramName === 'defeatReasonsIdOne'"
            :label="according2ReasonObj[ruleForm.resultReason].label"
            prop="defeatReasonsIdModel"
          >
            <el-cascader v-model="ruleForm.defeatReasonsIdModel" :props="failModelLIST"></el-cascader>
          </el-form-item>
          <!-- 战败城市 -->
          <el-form-item
            v-else-if="accordingObj && according2ReasonObj[ruleForm.resultReason].paramName === 'defeatReasonsParvince'"
            :label="according2ReasonObj[ruleForm.resultReason].label"
            prop="defeatReasonsIdCity"
          >
            <!-- :prop="according2ReasonObj[ruleForm.resultReason].paramName" -->
            <el-cascader v-model="ruleForm.defeatReasonsIdCity" :options="listAllData" clearable></el-cascader>
          </el-form-item>
        </template>
        <!-- 预约 -->
        <template v-else-if="this.selectBtnNum == 15171008?true:false">
          <el-form-item label="预约时间" prop="invitationsDate">
            <el-date-picker
              v-model="ruleForm.invitationsDate"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-form-item>
          <!-- <el-form-item v-show="false" label="预约时间2" prop="invitationsDate">
            <el-date-picker
              v-model="ruleForm.invitationsDate2"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-form-item>-->
          <el-form-item label="下次跟进时间" prop="nextActionedDateA">
            <el-date-picker
              v-model="ruleForm.nextActionedDateA"
              type="datetime"
              placeholder="选择日期时间"
              default-time="23:59:00"
              format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="下次跟进备注">
            <el-input type="textarea" v-model="ruleForm.taskName"></el-input>
          </el-form-item>
        </template>
      </el-form>

      <FormPanel
        ref="formPanel"
        :list="formList1"
        :cols="2"
        :formType="type"
        labelWidth="110"
        :isSubmitBtn="false"
        @formChange="formChangeHandle"
      />
    </div>
    <p style="height:25px;"></p>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'center'
      }"
    >
      <el-button @click="closeDialog">取 消</el-button>
      <AjaxButton
        :click="saveFollow.bind(this, 'addRuleForm')"
        type="primary"
        :disabled="isTRUE"
      >保存并编辑档客</AjaxButton>
      <AjaxButton
        :click="saveDialog.bind(this, 'addRuleForm')"
        type="primary"
        :disabled="isDisabled"
      >保 存</AjaxButton>
    </div>
  </div>
</template>

<script>
import {
  updateFollowInfo,
  getFollowInfoById,
  getInvalidReason,
  getFinPanActionDate,
  queryVisitingModeInfo7,
  getAppointmentById,
  skipDefeatReason,
  defeatedDealer,
  getPendingTime //获取待定跟进时间
} from '@/api/potenCus/customer/customerFollowInfo';
import { queryTrackingTask } from '@/api/potenCus/basedata/followTask';
import { getIntentLevelsList } from '@/api/potenCus/customer/potenCusManage';
import { selectCompeteModels } from '@/api/potenCus/basedata/competitiveModels/index';
import { queryFollowWays } from '@/api/potenCus/basedata/followWays';
import { searchDefeatReason } from '@/api/potenCus/basedata/defeatreason';
import { dictionary } from '@/utils/dictMixin';
import { formatDates, formatDates_minute } from '@/utils/validate';
import AjaxButton from '@/components/AjaxButton';

import { getlistAllData } from '@/api/common/org/dealerCompany';
import moment from 'moment';
export default {
  name: 'followModal',
  mixins: [dictionary],
  props: {
    typeEdit: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'edit'
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    accordingObj() {
      return (
        this.selectBtnNum == 15171005 &&
        Object.keys(this.according2ReasonObj)
          .map(item => Number(item))
          .includes(this.ruleForm.resultReason)
      );
    }
  },
  data() {
    this.saveData = null;
    return {
      isBlue: '',
      isBlue1: '',
      isBlue2: '',
      isBlue3: '',
      isBlue4: '',
      clueStatus: '',
      Level: '',
      isShowDefeat: true,
      max: '', // 最大日期
      pickerOptions: {
        disabledDate: time => {
          const min = new Date();
          if (this.max != '' && this.max != null) {
            // const max = new Date(this.max)
            // console.log("max:",max);
            //限制最大日期
            return time.getTime() < min.getTime() || time.getTime() > this.max.getTime();
            //return time.getTime() < min.getTime();
          } else {
            return time.getTime() < min.getTime();
          }
        }
      },
      ruleForm: {
        actionStatus: '', //跟进结果
        invalidReason: '', //无效原因
        nextActionedDate: '', //继续下次跟进时间
        nextActionedDateA: '', //预约的下次跟进时间
        nextActionedDateB: '', //待定的下次跟进时间
        taskName: '', //跟进备注
        taskName1: '', //跟进备注
        invitationsDate: '', //预约时间
        resultReason: '', //战败原因
        actionDate: '',
        defeatReasonsIdOne: '', // 根据战败原因按需显示
        defeatReasonsIdDealer: '',
        defeatReasonsIdCity: '', // 战败城市
        defeatReasonsIdModel: '' // 战败车型
      },
      according2ReasonObj: {},
      rules: {
        actionStatus: [{ required: true, message: '请选择跟进结果', trigger: 'blur' }],
        invalidReason: [{ required: true, message: '请选择无效原因', trigger: 'blur' }],
        nextActionedDate: [{ required: true, message: '请选择下次跟进时间', trigger: 'blur' }],
        nextActionedDateA: [{ required: true, message: '请选择下次跟进时间', trigger: 'blur' }],
        nextActionedDateB: [{ required: true, message: '请选择下次跟进时间', trigger: 'blur' }],
        resultReason: [{ required: true, message: '请选择战败原因', trigger: 'blur' }],
        invitationsDate: [{ required: true, message: '请选择预约时间', trigger: 'blur' }],
        defeatReasonsIdCity: [{ required: true, message: '请选择战败城市', trigger: 'blur' }],
        defeatReasonsIdDealer: [{ required: true, message: '请选择战败经销商', trigger: 'blur' }],
        defeatReasonsIdModel: [{ required: true, message: '请选择战败车型', trigger: 'blur' }]
      },
      isDisabled: false, //表单重复提交
      isTRUE: false, // 跟进并编辑按钮禁用
      invalidReasonList: [],
      defeatReasonList: [],
      formList: this.createFormList(),
      formList1: this.createFormList1(),
      formList2: this.createFormList2(), // 意向级别
      page: {
        pageNum: 1,
        currentPage: 1,
        pageSize: 100,
        limit: 100,
        isValid: 10041001
      },
      dealerPage: {
        currentPage: 1,
        pageSize: 10000
      },
      selectBtnNum: '',
      clueType: '',
      listAllData: [],
      listCompeteModels: [],
      failModelLIST: {},
      accordingTaskList: [], // 跟进级别及跟进时间
      pendingTime: '', // 待定时间
      waitTIME: '', // 最大待定时间
      actionId: '',
      isRequest: !1,
      NEWintentLeve: '',
      ownerCode: ''

      // 禁用时间选择
      // pickerOptions(){
      //   return {
      //     disabledDate(time) {
      //       // const min = new Date().getTime();
      //       // const max = this.waitTIME
      //       // if (min) {
      //       //   return max > time.getTime() > min;
      //       // }
      //       return time.getTime() < Date.now() - 8.64e7;
      //     }
      //   }
      // },
    };
  },
  watch: {
    ruleForm() {
      // console.log(this.ruleForm.actionStatus,"ruleForm.actionStatus")
      if (this.ruleForm.actionStatus == 15171009) {
        this.isBlue = 'isBlue';
      } else if (this.ruleForm.actionStatus == 15171007) {
        this.isBlue1 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 15171005) {
        this.isBlue2 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 15171004) {
        this.isBlue3 = 'isBlue';
      } else if (this.ruleForm.actionStatus == 15171008) {
        this.isBlue4 = 'isBlue';
      }
    }
  },
  created() {
    this.getFollowList();
    this.getPending(); //获取待定时间
    this.init();
    this.getInvReason();
    this.getIntentLevels(); // 获取意向
    this.getDefReason();
    this.getCityList();
    this.getModelsList();
  },
  methods: {
    async init() {
      console.log(this.type, this.rowData, 'rowData890');
      this.rowData = { ...this.rowData };
      let curLevel = this.rowData.intentLevel ? this.rowData.intentLevel : this.rowData.originalLevel;
      // console.log(this.rowData.actionStatus, 'this.rowData.actionStatus');
      this.customerBusinessId = this.rowData.customerBusinessId;
      this.recordId = this.rowData.actionId;
      this.ownerCode = this.rowData.ownerCode;
      this.clueType = this.rowData.clueType;
      this.clueStatus = this.rowData.clueStatus;
      this.Level = this.rowData.intentLevel;
      if (this.Level == 15191008) {
        this.isShowDefeat = false;
      }
      // if (this.type === 'add1') {
      //展厅接待 exhibitionAdd   预约管理  orderAdd  跟进明细  add1
      if (this.type === 'exhibitionAdd' || this.type === 'add1') {
        if (this.rowData.planActionDate) {
          this.formList[0].initialValue = formatDates(Number(this.rowData.planActionDate));
        }
        this.getFollowWays();
        if (this.rowData) {
          this.formList.forEach(x => {
            x.initialValue = this.rowData[x.fieldName];
          });
          this.formList2.forEach(x => {
            if (x.fieldName === 'intentLevel') {
              console.log('意向级别到底是什么1', this.rowData.intentLevel);
              // O: 15191008, 订单客户级别
              // J: 15191004, 已成交客户级别
              // N: 15191005, 未定级意向级别  originalLevel
              if (this.rowData.intentLevel == 15191008 || this.rowData.intentLevel == 15191004 || this.rowData.originalLevel == 15191008 || this.rowData.originalLevel == 15191004) {
                this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
              }
              this.rowData.intentLevel == 15191005 ? '' : (x.initialValue = this.rowData.intentLevel);
              this.initNextActionDate(curLevel);
            } else {
              x.initialValue = this.rowData.intentLevel;
            }
          });
          if (this.rowData.businessAnally) {
            this.formList.find(item => item.fieldName === 'businessAnally').initialValue = this.rowData.businessAnally.split(',').map(x => parseInt(x));
            let tempList1 = this.formList.find(item => item.fieldName === 'businessAnally').itemList;
            let businessList1 = this.rowData.businessAnally.split(',').map(x => parseInt(x));
            console.log('商机分析itemList', tempList1);
            console.log('明细商机分析', businessList1);
            tempList1.forEach(x => {
              businessList1.forEach(y => {
                if (x.value == y) {
                  x.disabled = true;
                }
              });
            });
          }
        }
      }
      if (this.type === 'edit' || this.type === 'add') {
        console.log('点击跟进页面的跟进', this.rowData);
        this.clueType = this.rowData.clueType;
        this.recordVersion = this.rowData.recordVersion;
        this.selectBtnNum = this.rowData.actionStatus;
        console.log('isFollow', this.rowData.isFollow);
        if (this.rowData.isFollow && this.rowData.isFollow == 10041001) {
          this.isTRUE = true;
        }
        this.isActioned = 1;
        this.formList2.forEach(x => {
          if (x.fieldName === 'intentLevel') {
            console.log('跟进意向级别2', this.rowData.originalLevel);
            // O: 15191008, 订单客户级别
            // J: 15191004, 已成交客户级别
            // N: 15191005, 未定级意向级别  originalLevel
            if (this.rowData.intentLevel == 15191008 || this.rowData.intentLevel == 15191004 || this.rowData.originalLevel == 15191008 || this.rowData.originalLevel == 15191004) {
              this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
            }

            this.rowData.intentLevel == 15191005 ? '' : (x.initialValue = this.rowData.intentLevel);
            this.rowData.originalLevel == 15191005 ? '' : (x.initialValue = this.rowData.originalLevel);
            this.initNextActionDate(curLevel);
          } else {
            x.initialValue = this.rowData[x.fieldName];
          }
        });
        this.getFollowInfo();
        let rowData = { ...this.rowData };
        this.ruleForm = this.rowData;
        this.ruleForm.taskName = '';
        // console.log('看一下数据',this.ruleForm)
        this.isDisabled = false;
      }
      //预约管理过来的数据处理
      if (this.type === 'orderAdd') {
        // if (this.typeEdit == 'typeEdit') {
        //   console.log(this.typeEdit, '展厅typeEdit');
        //   this.formList.find(item => item.fieldName === 'actionedWay').hidden = true;
        // }
        await getFinPanActionDate(this.rowData.customerBusinessId).then(res => {
          // console.log(res, '展厅res',);
          this.formList.find(item => item.fieldName === 'planActionDate').initialValue = res.data.planActionDate;
          if (res) {
            this.formList.forEach(x => {
              if (x.fieldName === 'intentLevel') {
                console.log('intentLevel', res.data.intentLevel);
                if (res.data.intentLevel == 15191008 || res.data.intentLevel == 15191004) {
                  this.formList.splice(4, 1);
                }
                res.data.intentLevel == 15191005 ? '' : (x.initialValue = res.data.intentLevel);
                this.initNextActionDate(res.data.intentLevel);
              } else {
                x.initialValue = res.data[x.fieldName];
              }
            });
          }
          console.log(res.data, '预约管理');
          this.formList.find(item => item.fieldName === 'actionedWay').initialValue = res.data.actionedWay;
          this.clueType = res.data.clueType;
          this.actionId = res.data.actionId;
        });
        console.log(this.formList, 'this.formList[0]');
        this.getQueryVisitingModeInfo7();
      }
    },
    selectChangeHandle(rows) {
      if (!rows.length) return;
      this.selectedRow = rows[0];
    },
    createFormList() {
      return [
        {
          type: 'DATE',
          label: '计划跟进时间',
          fieldName: 'planActionDate',
          disabled: true,
          dateType: 'date',
          format: 'yyyy-MM-dd HH:mm:ss',
          initialValue: '',
          selfCols: 2,
          placeholder: '计划跟进时间'
        },
        {
          type: 'TEXT_AREA',
          label: '跟进备注',
          fieldName: 'taskNameScene',
          selfCols: 2,
          disabled: true,
          placeholder: '跟进备注'
        },
        {
          type: 'TEXT_AREA',
          label: '跟进批注',
          fieldName: 'markup',
          selfCols: 2,
          disabled: true,
          placeholder: '跟进批注'
        },
        {
          type: 'MULTIPLE_CHECKBOX',
          label: '商机分析',
          fieldName: 'businessAnally',
          placeholder: '请选择',
          selfCols: 2,
          initialValue: '',
          itemList: [
            { value: 70431001, text: '邀约进店', disabled: false },
            { value: 70431002, text: '建立关系', disabled: false },
            { value: 70431003, text: '需求分析', disabled: false },
            { value: 70431004, text: '产品介绍', disabled: false },
            { value: 70431005, text: '试乘试驾', disabled: false },
            { value: 70431006, text: '异议处理', disabled: false },
            { value: 70431007, text: '价格商谈', disabled: false },
            { value: 70431008, text: '定金订单', disabled: false }
          ]
        },
        {
          type: 'SELECT',
          label: '跟进方式',
          fieldName: 'actionedWay',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          hidden: false,
          rules: [{ required: true, message: '请选择跟进方式', trigger: 'change' }]
        },
        {
          type: 'TEXT_AREA',
          label: '本次跟进情形',
          fieldName: 'actionedScene',
          selfCols: 2,
          placeholder: '请输入',
          initialValue: ''
        }
      ];
    },
    createFormList2() {
      return [
        {
          type: 'SELECT',
          label: '意向级别',
          fieldName: 'intentLevel',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          hidden: true,
          disabled: false,
          rules: [{ required: true, message: '请选择意向级别', trigger: 'change' }],
          change: e => {
            this.initNextActionDate(e);
          }
        }
      ];
    },
    createFormList1() {
      return [
        {
          type: 'UPLOAD_IMG',
          label: '上传图片',
          fieldName: 'followPicture',
          valueType: 'Array',
          upload: {
            actionUrl: '/api/file/oss/upload',
            fixedSize: [5, 3],
            limit: 3,
            isCalcHeight: true
          }
        }
      ];
    },
    // 更新下次跟进时间
    initNextActionDate(intentLevel) {
      console.log('跟进意向级别更新时间', intentLevel);
      console.log('跟进意向级别更新时间-----', this.accordingTaskList);
      let days = null;
      try {
        // days = this.accordingTaskList.find(item => item.intentLevel === intentLevel)['intervalDays']
        //2020-02-10  将intervalDays改为shopIntervalDays，也就是跟进规则的间隔时间使用经销商端自定义的
        days = this.accordingTaskList.find(item => item.intentLevel === intentLevel).shopIntervalDays;
        let n = new Date();
        n.setDate(n.getDate() + days);
        console.log('n:', n);
        this.max = n;
      } catch (e) {}
      if (!days) {
        return;
      }

      this.$set(
        this.ruleForm,
        'nextActionedDate',
        moment(moment().endOf('day'))
          .add(days, 'days')
          .valueOf()
      );
      this.$set(
        this.ruleForm,
        'nextActionedDateA',
        moment(moment().endOf('day'))
          .add(days, 'days')
          .valueOf()
      );
      this.$set(
        this.ruleForm,
        'nextActionedDateB',
        moment()
          .add(this.pendingTime, 'hours')
          .valueOf()
      );
      this.waitTIME = this.$set(
        this.ruleForm,
        'nextActionedDateB',
        moment()
          .add(this.pendingTime, 'hours')
          .valueOf()
      );

      this.$forceUpdate();
    },
    // 根据跟进结果来动态显示意向级别
    selectBtn(num) {
      console.log('num', num);
      console.log('selectBtn', this.rowData);
      console.log('看意向级别', this.rowData.originalLevel, this.rowData.intentLevel, this.NEWintentLeve);
      this.selectBtnNum = num;
      this.isBlue = '';
      this.isBlue1 = '';
      this.isBlue2 = '';
      this.isBlue3 = '';
      this.isBlue4 = '';
      this.ruleForm.actionStatus = num;
      if (this.rowData.originalLevel === 15191005 || this.rowData.intentLevel === 15191005 || this.NEWintentLeve === 15191005) {
        this.formList2.find(item => item.fieldName === 'intentLevel').initialValue = '';
      } else {
        let newIntentLevel = this.rowData.intentLevel ? this.rowData.intentLevel : this.NEWintentLeve;
        this.formList2.find(item => item.fieldName === 'intentLevel').initialValue = newIntentLevel;
        // this.formList2.find(item => item.fieldName ==='intentLevel').initialValue = this.rowData.originalLevel?this.rowData.originalLevel:this.NEWintentLeve
      }
      if (this.ruleForm.actionStatus == 15171009) {
        this.isBlue = 'isBlue';
        this.isTRUE = true;
        this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
      } else if (this.ruleForm.actionStatus == 15171007) {
        this.isBlue1 = 'isBlue';
        this.isTRUE = true;
        this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
      } else if (this.ruleForm.actionStatus == 15171005) {
        this.isBlue2 = 'isBlue';
        this.isTRUE = true;
        this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
      } else if (this.ruleForm.actionStatus == 15171004) {
        this.isBlue3 = 'isBlue';
        if (this.rowData.isFollow != 10041001) {
          this.isTRUE = false;
        }
        if (this.rowData.originalLevel === 15191004 || this.rowData.originalLevel === 15191008 || this.rowData.intentLevel === 15191008 || this.rowData.intentLevel === 15191004) {
          this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
        } else {
          this.formList2.find(item => item.fieldName === 'intentLevel').hidden = false;
        }
      } else if (this.ruleForm.actionStatus == 15171008) {
        this.isBlue4 = 'isBlue';
        if (this.rowData.isFollow != 10041001) {
          this.isTRUE = false;
        }
        if (this.rowData.originalLevel === 15191004 || this.rowData.originalLevel === 15191008 || this.rowData.intentLevel === 15191008 || this.rowData.intentLevel === 15191004) {
          this.formList2.find(item => item.fieldName === 'intentLevel').hidden = true;
        } else {
          this.formList2.find(item => item.fieldName === 'intentLevel').hidden = false;
        }
      }
      if (this.rowData.originalLevel) {
        this.initNextActionDate(this.rowData.originalLevel);
      } else {
        this.initNextActionDate(this.rowData.intentLevel);
      }
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    // 获取跟进明细
    async getFollowInfo() {
      const res = await getFollowInfoById(this.recordId, this.ownerCode);
      this.getFollowWays();
      if (res.resultCode === 200) {
        console.log('跟进明细res200', res);
        if (res.data.businessAnally) {
          let tempList = this.formList.find(item => item.fieldName === 'businessAnally').itemList;
          let businessList = res.data.businessAnally.split(',').map(x => parseInt(x));
          console.log('商机分析itemList', tempList);
          console.log('明细商机分析', businessList);
          tempList.forEach(x => {
            businessList.forEach(y => {
              if (x.value == y) {
                x.disabled = true;
              }
            });
          });
        }
        this.formList.forEach(x => {
          if (x.fieldName === 'businessAnally') {
            x.initialValue = res.data[x.fieldName] ? res.data[x.fieldName].split(',').map(x => parseInt(x)) : [];
          } else {
            x.initialValue = res.data[x.fieldName];
          }
        });
        this.formList2.find(item => item.fieldName === 'intentLevel').initialValue = res.data.intentLevel;
        this.NEWintentLeve = res.data.intentLevel;
        this.initNextActionDate(res.data['intentLevel']);
        this.clueStatus = res.data.clueStatus;
        if (res.data.actionStatus != 15171004 || res.data.actionStatus != 15171005 || res.data.actionStatus != 15171007 || res.data.actionStatus != 15171008 || res.data.actionStatus != 15171009) {
          this.ruleForm.actionStatus = '';
        }
        // this.clueType = res.data.clueType;
      }
    },
    //预约管理--过来的处理
    getQueryVisitingModeInfo7() {
      queryVisitingModeInfo7().then(res => {
        // console.log(res.data.records,"156")
        res.data.records.forEach(x => {
          this.formList.find(item => item.fieldName === 'actionedWay').itemList.push({ value: x.basedataId, text: x.basedataName });
        });
      });
    },
    // 战败经销商
    async getDealerLIST() {
      let dealerList = [];
      const res = await defeatedDealer(this.dealerPage);
      // console.log('战败经销商', res)
      if (res.resultCode === 200) {
        dealerList = res.data.records.map(item => {
          return {
            text: item.dealerName,
            value: item.dealerId
          };
        });
      }
      return dealerList;
    },
    // 意向级别
    async getIntentLevels() {
      const res = await getIntentLevelsList();
      // console.log('意向', res)
      let temp = res.data;
      const levelList = this.createDictList('1519');
      // console.log('意向111', levelList)
      let aimValueList = [];
      temp.forEach(item => {
        item.basedataCode = Number(item.basedataCode);
        if (aimValueList.length == 0) {
          aimValueList.push(item.basedataCode);
        } else {
          aimValueList.includes(item.basedataCode) ? '' : aimValueList.push(item.basedataCode);
        }
      });
      let aimList = aimValueList.map(item => {
        return levelList.find(x => x.value == item);
      });
      // console.log('意向级别aimList', aimList)
      this.formList2.find(item => item.fieldName === 'intentLevel').itemList = aimList.map(x => ({ value: x.value, text: x.text }));
      // console.log('surprise',aimList, aimValueList)
    },
    // 无效原因
    async getInvReason() {
      const res = await getInvalidReason(this.page);
      // console.log('无效',res)
      if (res.resultCode === 200) {
        this.invalidReasonList = res.data.records;
      }
    },
    // 跟进任务
    async getFollowList() {
      let params = {
        type: 1,
        pageNum: 1,
        currentPage: 1,
        pageSize: 20,
        limit: 20
      };
      const res = await queryTrackingTask(params);
      console.log('跟进任务', res);
      if (res.resultCode === 200) {
        // this.accordingTaskList = res.data.records
        this.accordingTaskList = res.data;
      }
    },
    // 获取待定时间
    async getPending() {
      const res = await getPendingTime();
      console.log('待定时间', res.data);
      if (res.resultCode === 200) {
        this.pendingTime = res.data;
      }
    },
    // 下拉change
    async currentSel(selVal) {
      // let carList = [];
      let dealerList = [];
      // await this.selectModels().then(val => {
      //   carList = val;
      // });
      await this.getDealerLIST().then(res => {
        dealerList = res;
      });
      const res = await skipDefeatReason();
      console.log('战败跳转', selVal, res);
      let curList = res.data;
      curList.forEach(item => {
        if (item.param === 'modelParam') {
          this.according2ReasonObj[Number(item.paramType)] = {
            label: '战败车型',
            paramName: 'defeatReasonsIdOne',
            list: []
          };
        } else if (item.param === 'dealerParam') {
          this.according2ReasonObj[Number(item.paramType)] = {
            label: '战败经销商',
            paramName: 'defeatReasonsIdThree',
            list: dealerList
          };
        } else if (item.param === 'cityParam') {
          this.according2ReasonObj[Number(item.paramType)] = {
            label: '战败城市',
            paramName: 'defeatReasonsParvince',
            list: []
          };
        }
      });
      // this.ruleForm.defeatReasonsIdOne = ['20','2434']
      // 强制更新
      this.according2ReasonObj = JSON.parse(JSON.stringify(this.according2ReasonObj));
    },
    // 是否预约
    async getIsAppointment() {
      const res = await getAppointmentById(this.rowData.customerBusinessId);
      console.log('是否预约', res);
      if (res.resultCode === 200) {
        return;
      } else {
        this.$message.info(res.errMsg);
        return false;
      }
    },
    // 跟进方式
    async getFollowWays() {
      const res = await queryFollowWays(this.page);
      // console.log('跟进方式',res)
      if (res.resultCode === 200) {
        let waysData = res.data.records;
        this.formList.find(item => item.fieldName === 'actionedWay').itemList = waysData.map(x => ({ value: x.basedataId, text: x.basedataName }));
        waysData.forEach(x => {
          if (x.basedataName == '电话') {
            this.formList.find(item => item.fieldName === 'actionedWay').initialValue = x.basedataId;
          } else {
            this.formList.find(item => item.fieldName === 'actionedWay').initialValue = '';
          }
        });
      }
    },
    // 战败原因
    async getDefReason() {
      const res = await searchDefeatReason(this.page);
      // console.log('战败',res)
      if (res.resultCode === 200) {
        this.defeatReasonList = res.data.records;
      }
    },
    saveDialog(formName) {
      // this.$refs.formPanel.SUBMIT_FORM();
      // this.$refs.formPanel2.SUBMIT_FORM();
      // let istrue =false
      // console.log(this.formList,"formList")
      // if(this.isRequest) return;
      // this.isRequest = !0;formPanel
      this.$refs[formName].validate(valid => {
        if (valid && this.$refs.formPanel.SUBMIT_FORM() && this.formList.find(x => x.fieldName == 'actionedWay').initialValue && this.$refs.formPanel2.SUBMIT_FORM()) {
          this.save();
        } else {
          this.$message.info('请填写必填项!');
          return false;
        }
      });
    },
    saveFollow(formName) {
      // this.$refs.formPanel.SUBMIT_FORM();
      // this.$refs.formPanel2.SUBMIT_FORM();
      // if(this.isRequest) return !1;
      // this.isRequest = !0;
      this.$refs[formName].validate(valid => {
        if (valid && this.$refs.formPanel.SUBMIT_FORM() && this.$refs.formPanel2.SUBMIT_FORM()) {
          this.saveFollowInfo();
        } else {
          this.$message.info('请填写必填项');
          return false;
        }
      });
    },

    async save() {
      this.isDisabled = true;
      let { selectBtnNum } = this;
      let ruleForm = JSON.parse(JSON.stringify(this.ruleForm));
      // console.log(ruleForm.invitationsDate,'预约时间') //日期对象 不需要new Date处理
      // console.log(ruleForm.nextActionedDate,'待定下次跟进时间1') //日期对象 不需要new Date处理
      // console.log(ruleForm.nextActionedDateA,'预约下次跟进时间2') //日期对象 不需要new Date处理
      // console.log(this.selectBtnNum,'按钮')
      if (ruleForm.invalidReason) {
        ruleForm.resultReason = ruleForm.invalidReason;
      }
      console.log(this.saveData, ruleForm, '测试saveObj数据');
      if (selectBtnNum == 15171008) {
        // 预约
        ruleForm.nextActionedDate = new Date(ruleForm.nextActionedDateA).getTime();
      } else if (selectBtnNum == 15171004) {
        // 继续
        ruleForm.nextActionedDate = new Date(ruleForm.nextActionedDate).getTime();
      } else if (selectBtnNum == 15171007) {
        // 待定
        ruleForm.nextActionedDate = new Date(ruleForm.nextActionedDateB).getTime();
      }
      let saveObj = { ...ruleForm, ...this.saveData };
      saveObj['recordVersion'] = this.recordVersion;
      saveObj['actionedScene'] = this.formList.find(item => item.fieldName === 'actionedScene').initialValue;
      saveObj['factIntentLevel'] = this.formList2.find(item => item.fieldName === 'intentLevel').initialValue;
      saveObj['planActionDate'] = new Date(this.formList[0].initialValue).getTime();
      saveObj['invitationsDate'] = new Date(ruleForm.invitationsDate).getTime();
      saveObj['clueType'] = this.clueType;
      saveObj['actionedWay'] = this.formList.find(item => item.fieldName === 'actionedWay').initialValue ? this.formList.find(item => item.fieldName === 'actionedWay').initialValue : '';
      saveObj['intentLevel'] = this.formList2.find(item => item.fieldName === 'intentLevel').initialValue;
      let temp = this.formList.find(item => item.fieldName === 'businessAnally').initialValue;
      saveObj['businessAnally'] = temp ? temp.toString() : '';
      saveObj.isEditPoten = 10041002;

      if (typeof saveObj.defeatReasonsIdCity === 'object') {
        saveObj.defeatReasonsParvince = saveObj.defeatReasonsIdCity[0];
        saveObj.defeatReasonsCity = saveObj.defeatReasonsIdCity[1];
      }
      console.log('跟进结果', this.ruleForm.actionStatus);
      console.log('按钮', this.selectBtnNum);
      console.log('跟进-仅保存', saveObj);
      // 继续
      let nextDate = new Date(ruleForm.nextActionedDate).getTime();
      console.log('继续的跟进时间', nextDate);

      let nextDateB = new Date(ruleForm.nextActionedDateB).getTime();
      console.log('待定小时数', this.pendingTime);
      console.log('最大待定时间', this.waitTIME);
      console.log('待定的跟进时间', nextDateB);
      let date = new Date();
      let curTime = formatDates_minute(date);
      let maxTIME = formatDates_minute(this.waitTIME);
      console.log('显示的两个时间', curTime, maxTIME);
      console.log('超出时间', (this.waitTIME - nextDateB) / 1000 / 3600);
      if ((this.waitTIME - nextDateB) / 1000 / 3600 > this.pendingTime || (this.waitTIME - nextDateB) / 1000 / 3600 < 0) {
        this.$message.info(`待定时间范围应在${curTime}和${maxTIME}之间!`);
        this.isDisabled = false;
        return;
      } else {
        //预约管理过来
        if (this.type == 'orderAdd') {
          console.log('预约管理过来20191128处理');
          saveObj.actionId = this.actionId;
          this.isActioned = this.actionId;
          saveObj.clueType = this.clueType;
          saveObj.customerBusinessId = this.rowData.customerBusinessId;

          this.getIsAppointment();
          updateFollowInfo({ ...saveObj, actionId: this.actionId, customerBusinessId: this.customerBusinessId }, this.isActioned, this.clueType)
            .then(res => {
              // this.isRequest = !1;
              if (res.resultCode === 200) {
                this.isDisabled = false;
                this.closeDialog('refresh');
                this.$message.success('保存成功!');
              } else {
                this.isDisabled = false;
                // this.$message.info('请填写必填项');
              }
            })
            .catch(err => {
              this.isDisabled = false;
              // this.$message.info(err.errMsg);
            });
        } else {
          this.getIsAppointment();
          updateFollowInfo({ ...saveObj, actionId: this.recordId, customerBusinessId: this.customerBusinessId, ownerCode: this.ownerCode }, this.isActioned, this.clueType)
            .then(res => {
              // this.isRequest = !1;
              if (res.resultCode === 200) {
                this.isDisabled = false;
                this.closeDialog('refresh');
                this.$message.success('保存成功!');
              } else {
                this.isDisabled = false;
                // this.$message.info('请填写必填项');
              }
            })
            .catch(err => {
              this.isDisabled = false;
              // this.$message.info(err.errMsg);
            });
        }
      }
    },

    async saveFollowInfo() {
      this.isTRUE = true;
      let { selectBtnNum } = this;
      let ruleForm = JSON.parse(JSON.stringify(this.ruleForm));
      if (ruleForm.invalidReason) {
        ruleForm.resultReason = ruleForm.invalidReason;
      }
      if (selectBtnNum == 15171008) {
        ruleForm.nextActionedDate = new Date(ruleForm.nextActionedDateA).getTime();
      } else if (selectBtnNum == 15171004) {
        ruleForm.nextActionedDate = new Date(ruleForm.nextActionedDate).getTime();
      } else if (selectBtnNum == 15171007) {
        ruleForm.nextActionedDate = new Date(ruleForm.nextActionedDateB).getTime();
      }
      console.log('最大待定时间', this.waitTIME);
      console.log('待定小时数', this.pendingTime);
      let saveObj = { ...ruleForm, ...this.saveData };
      saveObj['recordVersion'] = this.recordVersion;
      saveObj['actionedScene'] = this.formList.find(item => item.fieldName === 'actionedScene').initialValue;
      saveObj['factIntentLevel'] = this.formList2.find(item => item.fieldName === 'intentLevel').initialValue;
      saveObj['planActionDate'] = new Date(this.formList[0].initialValue).getTime();
      saveObj['invitationsDate'] = new Date(ruleForm.invitationsDate).getTime();
      saveObj['clueType'] = this.clueType;
      saveObj['actionedWay'] = this.formList.find(item => item.fieldName === 'actionedWay').initialValue ? this.formList.find(item => item.fieldName === 'actionedWay').initialValue : '';
      saveObj['intentLevel'] = this.formList2.find(item => item.fieldName === 'intentLevel').initialValue;
      let temp = this.formList.find(item => item.fieldName === 'businessAnally').initialValue;
      saveObj['businessAnally'] = temp ? temp.toString() : '';
      saveObj.isEditPoten = 10041001;

      if (typeof saveObj.defeatReasonsIdCity === 'object') {
        saveObj.defeatReasonsParvince = saveObj.defeatReasonsIdCity[0];
        saveObj.defeatReasonsCity = saveObj.defeatReasonsIdCity[1];
      }
      console.log('跟进结果', this.ruleForm.actionStatus);
      console.log('跟进-保存并编辑潜客', saveObj, this.type);

      let nextDateB = new Date(ruleForm.nextActionedDateB).getTime();
      console.log('待定小时数', this.pendingTime);
      console.log('最大待定时间', this.waitTIME);
      console.log('保存的待定时间', nextDateB);
      let date = new Date();
      let curTime = formatDates_minute(date);
      let maxTIME = formatDates_minute(this.waitTIME);
      console.log('显示的两个时间', curTime, maxTIME);
      console.log('超出时间', (this.waitTIME - nextDateB) / 1000 / 3600);
      if ((this.waitTIME - nextDateB) / 1000 / 3600 > this.pendingTime || (this.waitTIME - nextDateB) / 1000 / 3600 < 0) {
        this.$message.info(`待定时间范围应在${curTime}和${maxTIME}之间!`);
        this.isDisabled = false;
        return;
      } else {
        //预约管理过来
        if (this.type == 'add' || this.type == 'orderAdd') {
          console.log('预约管理过来20191128处理');
          saveObj.actionId = this.actionId;
          // this.isActioned = this.rowData.actionId;
          this.isActioned = this.actionId;
          saveObj.clueType = this.clueType;
          saveObj.customerBusinessId = this.rowData.customerBusinessId;
          this.getIsAppointment();
          updateFollowInfo({ ...saveObj, actionId: this.actionId, customerBusinessId: this.customerBusinessId }, this.isActioned, this.clueType)
            .then(res => {
              // this.isRequest = !1;
              if (res.resultCode === 200) {
                console.log('预约管理编辑潜客', res);
                this.isTRUE = false;
                if (res.data.actionStatus != 15171005 || res.data.actionStatus != 15171007 || res.data.actionStatus != 15171009) {
                  this.$message.success('保存成功并编辑潜客');
                  this.closeDialog1(res);
                } else {
                  this.isTRUE = false;
                  this.$message.info('当前潜客不可编辑');
                  this.closeDialog1();
                }
                // this.closeDialog('refresh');
                // this.$message.success('保存成功!');
              } else {
                // this.$message.info('请填写必填项');
                this.isTRUE = false;
              }
            })
            .catch(err => {
              this.isTRUE = false;
              // this.$message.info(err.errMsg);
            });
        } else {
          this.getIsAppointment();
          // this.isTRUE=true
          updateFollowInfo({ ...saveObj, actionId: this.recordId, customerBusinessId: this.customerBusinessId, ownerCode: this.ownerCode }, this.isActioned, this.clueType)
            .then(res => {
              // this.isRequest = !1;
              if (res.resultCode === 200) {
                console.log('并新增', res);
                this.isTRUE = false;
                if (res.data.actionStatus != 15171005 || res.data.actionStatus != 15171007 || res.data.actionStatus != 15171009) {
                  this.$message.success('保存成功并编辑潜客');
                  this.closeDialog1(res);
                } else {
                  this.isTRUE = false;
                  this.$message.info('当前潜客不可编辑');
                  this.closeDialog1();
                }
              } else {
                this.isTRUE = false;
                // this.$message.info('请填写必填项');
              }
            })
            .catch(err => {
              this.isTRUE = false;
              // this.$message.info(err.errMsg);
            });
        }
      }
    },
    closeDialog(param) {
      this.$emit('close', false, param);
      this.ruleForm = {};
    },
    closeDialog1(param) {
      this.$emit('fatherClose', param);
      console.log('打印打印去编辑潜客', param);
      this.closeDialog();
    },
    // 战败车型 --竞品
    async getModelsList() {
      const Array1 = await selectCompeteModels(1);
      // console.log('一级', Array1)
      const Array2 = await selectCompeteModels(2);
      // console.log('二级', Array2)
      this.failModelLIST = {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level, value } = node;
          console.log(node);
          setTimeout(() => {
            const nodes =
              level == 0
                ? Array1.data.map(item => ({
                    value: item.failModelId,
                    label: `${item.failBrand}`,
                    leaf: false
                  }))
                : Array2.data
                    .map(item => ({
                      value: item.failModelId,
                      label: `${item.failSeries}`,
                      parentId: `${item.parentId}`,
                      leaf: true
                    }))
                    .filter(item => item.parentId == value);
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes);
          }, 5);
        }
      };
    },
    // 战败车型
    async selectModels() {
      let list = [];
      let res = await selectCompeteModels(1);
      // console.log('竞品品牌', res)
      if (res.resultCode === 200) {
        list = res.data.map(item => {
          return {
            text: item.failBrand,
            value: item.failModelId
          };
        });
      }
      return list;
    },
    // 战败城市
    async getCityList() {
      let self = this;
      //  console.log(this.provinceId,this.cityId,"this.formList3[89]")
      await getlistAllData().then(res => {
        // console.log('城市', res)
        let province = [],
          listAllData = [];
        listAllData = res.data;
        listAllData.forEach(x => {
          // 筛选省
          if (x.parentRegionId == null) {
            province.push({ label: x.regionName, value: `${x.regionId}` });
          }
        });
        province.forEach(y => {
          let initCity = [];
          listAllData.forEach(x => {
            // 市
            if (x.parentRegionId == y.value) {
              initCity.push({ label: x.regionName, value: `${x.regionId}` });
            }
          });
          y.children = initCity;
        });
        this.listAllData = province;
        // console.log("省市",province)
      });
    }
  }
};
</script>

<style lang="less" scoped>
.isBlue {
  background: #ecf5ff;
}
.font {
  /deep/ .el-textarea__inner {
    font-family: inherit;
  }
}
</style>
